package com.eastfair.home.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.eastfair.auth.api.AuthServiceFeign;
import com.eastfair.auth.api.GlobalBusinessServiceFeign;
import com.eastfair.auth.api.RoleServiceFeign;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.*;
import com.eastfair.auth.entity.Role;
import com.eastfair.auth.enumeration.OrganizationOrgTypeEnum;
import com.eastfair.auth.enumeration.OrganizationVestTypeEnum;
import com.eastfair.auth.enumeration.RoleRoleTypeEnum;
import com.eastfair.auth.exceptioncode.AuthServiceExceptionCode;
import com.eastfair.auth.vo.RoleVo;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.home.dto.BindHomeServiceProviderRoleDTO;
import com.eastfair.home.dto.RemoveHomeServiceProviderRoleDTO;
import com.eastfair.home.exceptioncode.HomeExceptionCode;
import com.eastfair.home.service.HomeRegisterService;
import com.eastfair.home.vo.HomeRegisterDataVO;
import com.eastfair.jwt.service.JwtService;
import com.eastfair.venuebooking.api.ServiceProviderFeign;
import com.eastfair.venueservice.enumeration.ServiceProviderRoleEnum;
import com.eastfair.venueservice.enumeration.ServiceProviderTypeEnum;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 业务实现类
 * 服务项
 * </p>
 *
 * @author lyw
 * @date 2022-08-10
 */
@Slf4j
@Service
public class HomeRegisterServiceImpl implements HomeRegisterService {
    @Autowired
    private UserAccountServiceFeign userAccountServiceFeign;
    @Autowired
    private AuthServiceFeign authServiceFeign;
    @Autowired
    private RoleServiceFeign roleServiceFeign;
    @Autowired
    private GlobalBusinessServiceFeign globalBusinessServiceFeign;
    @Autowired
    JwtService jwtService;
    @Autowired
    private ServiceProviderFeign serviceProviderFeign;

    /**
     * 主场服务商注册
     *
     * @param userAccountDto
     * @return
     */
    @Override
    public HomeRegisterDataVO registerHomeUser(UserAccountDto userAccountDto) {
        log.info("HomeRegisterServiceImpl +++++ registerHomeUser -主场服务商注册 params={}", JSONObject.toJSON(userAccountDto));
        R<UserAccountVo> r = userAccountServiceFeign.registerSubSystemUser(userAccountDto);
        if (!r.getIsSuccess()) {
            throw BizException.wrap(r.getCode(), r.getMsg());
        }
        //查询主场服务商信息
        R<ServiceProviderVO> serviceProviderVOR = serviceProviderFeign.getByUserId(r.getData().getId(), ServiceProviderTypeEnum.HOME_SERVICE_PROVIDER.getCode());        //token解析对象
        if (!serviceProviderVOR.getIsSuccess()) {
            throw BizException.wrap(serviceProviderVOR.getCode(), serviceProviderVOR.getMsg());
        }
        return HomeRegisterDataVO.builder().userAccountVo(r.getData()).serviceProviderVO(serviceProviderVOR.getData()).build();
    }

    /**
     * 主场用户附常规角色
     *
     * @param bindHomeServiceProviderRoleDTO
     * @return
     */
    @Override
    public Boolean bindHomeServiceProviderRole(BindHomeServiceProviderRoleDTO bindHomeServiceProviderRoleDTO) {
        log.info("bindHomeServiceProviderRole - 主场服务商注册, params={}", bindHomeServiceProviderRoleDTO);
        RegisterDTO registerDTO = new RegisterDTO();
        //创建顶级组织
        OrganizationDTO organizationDTO = new OrganizationDTO();
        //组织类型  搭建商
        organizationDTO.setOrgType(OrganizationOrgTypeEnum.P_COMPOSITE_COURT);
        //资源
        organizationDTO.setVestType(OrganizationVestTypeEnum.R);
        organizationDTO.setParentId(BusinessConstant.parentId);
        //公司名称
        organizationDTO.setName(bindHomeServiceProviderRoleDTO.getServiceProviderName());
        registerDTO.setOrganizationDTO(organizationDTO);
        //创建用户角色
        RoleDTO role = new RoleDTO();
        role.setRoleType(RoleRoleTypeEnum.P_COMPOSITE_COURT_ADMIN);
        role.setName(ServiceProviderRoleEnum.HOME_COMMON_ROLE.getDesc());
        role.setBusinessTag(bindHomeServiceProviderRoleDTO.getServiceProviderRole());
        registerDTO.setRoleDTO(role);
        //修改关联信息
        UserAccountDto accountDto = new UserAccountDto();
        accountDto.setId(bindHomeServiceProviderRoleDTO.getUserId());
        //主场id
        accountDto.setCourtId(bindHomeServiceProviderRoleDTO.getServiceProviderId());
        registerDTO.setUserAccountDto(accountDto);
        registerDTO.setTeamId(bindHomeServiceProviderRoleDTO.getServiceProviderId());
        log.info("registerDTO is {}", JSONObject.toJSONString(registerDTO));
        userAccountServiceFeign.registerServiceProvider(registerDTO);

        return Boolean.TRUE;
    }

    /**
     * 主场服务商移除角色
     * @param removeHomeServiceProviderRoleDTOList
     * @return
     */
    @Override
    public Boolean removeHomeServiceProviderRole(List<RemoveHomeServiceProviderRoleDTO> removeHomeServiceProviderRoleDTOList) {
        if(CollectionUtils.isEmpty(removeHomeServiceProviderRoleDTOList) || removeHomeServiceProviderRoleDTOList.size()==0){
            throw BizException.wrap(HomeExceptionCode.NOT_SERVICE_PROVIDER_NULL);
        }
        removeHomeServiceProviderRoleDTOList.forEach((s)->{
            ContextUtil.setTeamId(s.getServiceProviderId());
            //查询基础角色信息
            RoleDTO roleDTO =new RoleDTO();
            roleDTO.setBusinessTag(s.getServiceProviderRole());
            R<List<RoleVo>> queryRole = roleServiceFeign.queryRole(roleDTO);
            if(!queryRole.getIsSuccess()){
                throw BizException.wrap(queryRole.getCode(),queryRole.getMsg());
            }

            //角色id集合
            List<Long> roleIds= Lists.newArrayList();
            List<Long> ids = queryRole.getData().stream().map(RoleVo::getId).collect(Collectors.toList());
            roleIds.addAll(ids);
            List<Long> userIds = Lists.newArrayList();
            userIds.add(s.getUserId());
            UserRoleDto userRoleDto =new UserRoleDto();
            userRoleDto.setRoleIds(roleIds);
            userRoleDto.setUserIds(userIds);
            authServiceFeign.removeOrgRole(userRoleDto);
        });
        return Boolean.TRUE;
    }
}

